package top.appx.dao.impl;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import top.appx.dao.ArticleDao;
import top.appx.entity.ArticleEntity;
import top.appx.qo.ArticleQO;
import top.appx.util.StringUtil;
import top.appx.vo.Pager;

import java.util.List;

/**
 * Created by zwy on 2015-5-22.
 */
@Repository
public class ArticleDaoImpl extends BaseDaoImpl<ArticleEntity> implements ArticleDao {
      public Pager<ArticleEntity> queryByPage(ArticleQO bean, int page, int rows){
          Criteria c = this.getCurrentSession().createCriteria(ArticleEntity.class);
          int total = ((Number)c.setProjection(Projections.rowCount()).uniqueResult()).intValue();
          c.setProjection(null);
          c.addOrder(Order.desc("id"));
          c.setFirstResult((page-1)*rows);
          c.setMaxResults(rows);
          if(bean!=null) {
              if(!StringUtil.isEmptyOrNull(bean.getTitle())) {
                  c.add(Restrictions.like("title", "%" + bean.getTitle() + "%"));
              }
              if(bean.getFid()!=null){
                  c.add(Restrictions.eq("folderId",bean.getFid()));
              }
          }


          List list = c.list();
          Pager<ArticleEntity> result = new Pager<ArticleEntity>();
          result.setTotal(total);
          result.setRows(list);
          return result;
      }

    public List<ArticleEntity> homeList() {
        Criteria c = this.getCurrentSession().createCriteria(ArticleEntity.class);
        c.setMaxResults(10);
        List list = c.list();
        return list;
    }

    public List<ArticleEntity> homeNewest() {
        Criteria c = this.getCurrentSession().createCriteria(ArticleEntity.class);
        c.setMaxResults(10);
        c.addOrder(Order.desc("id"));
        List list = c.list();
        return list;
    }
}
